<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2020/1/3
 * Time: 14:39
 */

namespace app\index\controller;


use app\IndexBaseController;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Db;
use tools\Email;
use tools\Verify;

class Mine extends IndexBaseController
{

    /**
     * 登录
     * @return \think\response\View
     */
    function login()
    {
        if ($this->request->method() == 'GET') {
            return view('login');
        } else {
            try {
                validate(\app\index\validate\Mine::class)
                    ->scene('login')
                    ->check($this->reqdata);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }
            if(strpos($this->reqdata['username'], '@')!==false){
                $where['email'] = $this->reqdata['username'];
            }else if(preg_match('/[a-zA-Z]/',$this->reqdata['username'])){
                $where['username'] = $this->reqdata['username'];
            }else{
                $where['phone'] = $this->reqdata['username'];
            }
            $user = Db::name("login")->where($where)->find();
            if($user==null){
                $this->error('账户不存在');
            }
            $pwd = sha1(md5($this->reqdata['pwd'].$user['code']));
            if($pwd != $user['pwd']){
                $this->error('密码错误');
            }
            Db::name('login_log')->insert([
                'userid'=>$user['id'],
                'ip'=>$this->get_real_ip(),
                'time'=>$this->request->server('REQUEST_TIME')
            ]);
            $time = 0;
            if($this->reqdata['remember']==2){
                $time = 604800;

            }
            $sign = '';
            if($this->reqdata['remember'] != 1){
                $verify = new Verify(['codeLen' => 16, 'name' => '']);
                $sign = sha1($verify->generate());
                if ($this->reqdata['remember'] == 2) {
                    $this->reqdata['remember'] = $this->request->server('REQUEST_TIME') + $time;
                    cookie('userid', $user['id'], 604800);
                    cookie('rememberSign', $sign, 604800);
                } else {
                    Cookie::forever('userid', $user['id']);
                    Cookie::forever('rememberSign', $sign);
                }
            }
            Db::name("login")->where('id',$user['id'])->update([
                'rememberTime'=>$this->reqdata['remember'],
                'rememberSign'=>$sign
                ]);
            $userinfo = Db::name('user')->find($user['id']);
            session('userinfo', $userinfo);
            cache($user['id'].'.session_id',\think\facade\Session::getId());
            $this->success();
        }
    }

    /**
     * 注册
     * @return \think\response\View
     */
    function register()
    {
        if ($this->request->method() == 'GET') {
            return view('register');
        } else {
            try {
                validate(\app\index\validate\Mine::class)
                    ->scene('register')
                    ->check($this->reqdata);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }
            $data = $this->reqdata;
            $user = Db::name('login')->where('username',$data['username'])->find();
            if($user != null){
                $this->error('用户名已存在');
            }
            $verify = new Verify(['codeLen' => 8, 'name' => 'email']);
            if (!$verify->chack($this->reqdata['code'])) {
                $this->error('验证码错误或失效');
            }

            unset($data['repwd']);
            $data['code'] = $verify->generate();
            $data['pwd'] = sha1(md5($data['pwd'].$data['code']));
                Db::startTrans();
            try {
                $id = Db::name('login')->insertGetId($data);
                Db::name('user')->insert(['id' => $id,'createTime'=>$this->request->server('REQUEST_TIME')]);
                // 提交事务
                Db::commit();
                $status = true;
            } catch (\Exception $e) {
                $status = false;
                // 回滚事务
                Db::rollback();
            }
            if ($status) {
                Db::name('login_log')->insert([
                    'userid'=>$id,
                    'ip'=>$this->get_real_ip(),
                    'time'=>$this->request->server('REQUEST_TIME')
                ]);
                session('userinfo', ['id' => $id]);
                $this->success();
            } else {
                $this->error('注册失败，请稍后再试');
            }
        }
    }

    /**
     * 发送邮箱验证码
     */
    function email()
    {
        $mailcheck = $this->spamcheck($this->reqdata['email']);
        if ($mailcheck == FALSE) {
            $this->error('输入错误');
        } else {
            $email = Db::name('login')->where('email',$this->reqdata['email'])->find();
            if($email != null ){
                $this->error('邮箱已注册');
            }
            $verify = new Verify(['codeLen' => 8, 'name' => 'email']);
            $code = $verify->save_code();
            $subject = '注册验证码';
            $message = '<br/>你的注册验证码为：' . $code . '; 5分钟内有效';
            $email = new Email();
            $res = $email->sendMail(config('web.web_name'), $this->reqdata['email'], $subject, $message);
            if($res){
                $this->success();
            }else{
                $this->error('邮件发送失败，请稍后再试');
            }
        }
    }

    /**
     * 邮箱验证
     * @param $field
     * @return bool
     */
    function spamcheck($field)
    {
        $field = filter_var($field, FILTER_SANITIZE_EMAIL);
        if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}